/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.cred.industries.platform.view.main {
	
	import com.cred.industries.platform.business.TaskEvent;
	import com.cred.industries.platform.business.facade.MetricsFacade;
	import com.cred.industries.platform.view.account.Customers;
	import com.cred.industries.platform.view.account.Login;
	import com.cred.industries.platform.view.account.events.LoginEvents;
	
	import flash.desktop.NativeApplication;
	import flash.display.NativeWindow;
	import flash.events.Event;
	
	import mx.events.FlexEvent;
	import mx.managers.PopUpManager;
	
	import spark.components.Application;
	import spark.components.Group;
	
	public class Main extends Group {
		
		private var mLogin:Login = null;
		private var mCustomers:Customers = null;
		public function Main() {
			
			super();
			addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler, false, 0, true);
		}
		
		private function creationCompleteHandler(event:FlexEvent):void {
			
			setupView();
			registerListeners();
		}
		
		private function registerListeners():void {
			
			mLogin.addEventListener(LoginEvents.LOGIN_COMPLETE, loginComplete, false, 0, true);
			mLogin.addEventListener(LoginEvents.LOGIN_FAILED, loginFailed, false, 0, true);
			mLogin.addEventListener(LoginEvents.LOGIN_CANCELED, loginCanceled, false, 0, true);
			
			var appWindow:NativeWindow = this.stage.nativeWindow;
			appWindow.addEventListener(Event.CLOSING, closingHandler, false, 0, true);
		}
		
		private function setupView():void {
			
			mLogin = new Login();
			mLogin.verticalCenter = 0;
			mLogin.horizontalCenter = 0;
			mLogin.open(this, true);
			
			PopUpManager.centerPopUp(mLogin);
		}
		
		private function loginComplete(event:LoginEvents):void {
			
			mLogin.close();
			mLogin = null;
			
			MetricsFacade.get().appStarted();
			mCustomers = new Customers();
			mCustomers.open(this, true);
		}
		
		private function loginFailed(event:LoginEvents):void {
			
			mLogin.close();
			mLogin = null;
			NativeApplication.nativeApplication.exit();
		}
		
		private function loginCanceled(event:LoginEvents):void {
			
			mLogin.close();
			mLogin = null;
			NativeApplication.nativeApplication.exit();
		}
		
		private function closingHandler(event:Event):void {
			
			MetricsFacade.get().appClosed();
		}
	}
}